<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>View Task</title>
</head>
<body>
	<h2>Current To-Do List</h2>


<?php
/**
 * 本页用递归函数显示所有任务
 *
 * User: ford
 * Date: 15-7-24
 * Time: 上午8:49
 */

function make_list($parent) {
	//需要一个全局$tasks数组，这是为了演示，不要这样用
	global $tasks;

	echo '<ol>';

	foreach ($parent as $task_id => $todo) {
//		echo "<li>$todo";
		echo <<<EOT
		<li><input type="checkbox" name="tasks[$task_id]" value="done">$todo
EOT;
		//检查子任务
		if(isset($tasks[$task_id])) {
			make_list($tasks[$task_id]);
		}

		echo '</li>';
	}

	echo '</ol>';
}

/**
 * 这个函数的功能和上面的完全一样，但是它用的是静态变量，这是最好的做法，不要在函数中使用合局变量
 * @param $parent
 * @param null $all
 */
function make_list_static($parent, $all = null) {
	static $tasks;

	if(isset($all)) {
		$tasks = $all;
	}

	echo '<ol>';

	foreach ($parent as $task_id => $todo) {

		echo <<<EOT
		<li><label><input type="checkbox" name="tasks[$task_id]" value="done">$todo</label>
EOT;


		//检查子任务
		if(isset($tasks[$task_id])) {
			make_list_static($tasks[$task_id], $tasks);
		}

		echo '</li>';
	}

	echo '</ol>';

}

$dbc = mysqli_connect('localhost', 'root', 'al8840dd', 'test');
//查询所有未完成任务
$q = 'SELECT task_id, parent_id, task FROM tasks WHERE date_completed="0000-00-00 00:00:00" ORDER BY parent_id,date_added ASC';
$r = mysqli_query($dbc, $q);

$tasks = array();

while (list ($task_id, $parent_id, $task) = mysqli_fetch_array($r, MYSQLI_NUM)) {
	$tasks[$parent_id][$task_id] = $task;
}

echo '<pre>'. print_r($tasks, 1) . '</pre>';

//make_list($tasks[0]);

echo '<br />请选择已完成任务，并提交<br />';
echo '<form action="view_task.php" method="post">';
make_list_static($tasks[0],$tasks);
echo '<input name="submit" type="submit" value="提交">';
echo '</form>';

//下面测试数据提交情况
if(($_SERVER['REQUEST_METHOD'] == 'POST')
	&& isset($_POST['tasks'])
	&& is_array($_POST['tasks'])
	&& !empty($_POST['tasks'])) {

	$q = 'UPDATE tasks SET date_completed=NOW() WHERE task_id IN (';
	foreach($_POST['tasks'] as $task_id => $v) {
		$q .= $task_id . ',';
	}
	$q = substr($q, 0, -2) . ')';

	$r = mysqli_query($dbc, $q);

	if(mysqli_affected_rows($dbc) == count($_POST['tasks'])) {
		echo '<p>任务完成已提交！</p>';
	} else {
		echo '<p>部分任务完成没提交！</p>';
	}
}
?>
</body>
</html>
